package vip.zhenzicheng.algorithm.leetcode.binary_tree;

import vip.zhenzicheng.algorithm.TreeNode;

/**
 * <a href="https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/">二叉树的最近公共祖先 [中等]</a>
 *
 * @author zhenzicheng
 * @date 2022-07-01 09:54
 */
public class LowestCommonAncestorOfABinaryTree_236 {

  public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    /*找到p,q所在节点，终止递归或者找到叶子节点也没找到*/
    if (root == null || root == p || root == q) {
      return root;
    }

    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    if (left != null && right != null) {
      return root; // 找到最近公共祖先
    }

    return left != null ? left : right;
  }
}
